package individual.mamingchao.scratch_story.util;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 单例的 BeanCopyUtils
 *
 * TODO 范型的没实现
 * Created by mamingchao on 2020/12/25.
 */
public class BeanCopyUtils<T>{

    static BeanCopyUtils instance = new BeanCopyUtils();

    private BeanCopyUtils(){

    }

    static public BeanCopyUtils getInstance(){
        return instance;
    }



    public <F> List<T> BeanListCopy(List<F> list, Class<T> destclazz) {
        List<T> resultList = new ArrayList<T>();

        list.stream().forEach(f -> {
            T t = getNewInstance();

            BeanUtils.copyProperties(f,t);
            resultList.add(t);
        });
        return resultList;
    }

    private  T getNewInstance() {
        Type superclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = null;
        if (superclass instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) superclass;
            Type[] typeArray = parameterizedType.getActualTypeArguments();
            if (typeArray != null && typeArray.length > 0) {
                Class<T> clazz = (Class<T>) typeArray[0];
                try {
                    return clazz.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
